"""
FastAPI应用主文件
"""
import logging
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import uvicorn

from .routes import api_router
from ..config.settings import WEB_CONFIG
from .. import __version__

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# 创建FastAPI应用
app = FastAPI(
    title="向量库操作系统",
    description="文件管理、向量库和检索系统",
    version=__version__,
    docs_url="/docs",
    redoc_url="/redoc"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境中应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含API路由
app.include_router(api_router)

# 静态文件服务
try:
    app.mount("/static", StaticFiles(directory="vector_system/web/static"), name="static")
except:
    pass

# 模板
try:
    templates = Jinja2Templates(directory="vector_system/web/templates")
except:
    templates = None

@app.get("/", response_class=HTMLResponse)
async def root(request: Request):
    """根路径 - 返回Web界面"""
    if templates:
        return templates.TemplateResponse("index.html", {"request": request})
    else:
        return """
        <!DOCTYPE html>
        <html>
        <head>
            <title>向量库操作系统</title>
            <meta charset="utf-8">
            <style>
                body { font-family: Arial, sans-serif; margin: 40px; }
                .container { max-width: 800px; margin: 0 auto; }
                .header { text-align: center; margin-bottom: 40px; }
                .api-links { margin: 20px 0; }
                .api-links a { display: block; margin: 10px 0; padding: 10px; 
                              background: #f0f0f0; text-decoration: none; color: #333; }
                .api-links a:hover { background: #e0e0e0; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>向量库操作系统</h1>
                    <p>文件管理、向量库和检索系统</p>
                    <p>版本: {version}</p>
                </div>
                
                <div class="api-links">
                    <h2>API接口</h2>
                    <a href="/docs">API文档 (Swagger UI)</a>
                    <a href="/redoc">API文档 (ReDoc)</a>
                    <a href="/api/v1/system/health">系统健康检查</a>
                    <a href="/api/v1/system/stats">系统统计信息</a>
                </div>
                
                <div class="api-links">
                    <h2>主要功能</h2>
                    <a href="/docs#/API/upload_file">文件上传</a>
                    <a href="/docs#/API/get_file_list">文件列表</a>
                    <a href="/docs#/API/search">文档搜索</a>
                    <a href="/docs#/API/get_system_stats">系统监控</a>
                </div>
            </div>
        </body>
        </html>
        """.format(version=__version__)

@app.get("/health")
async def health():
    """简单的健康检查"""
    return {"status": "healthy", "version": __version__}

@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logging.info("向量库操作系统启动中...")
    logging.info(f"版本: {__version__}")
    logging.info(f"配置: {WEB_CONFIG}")

@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logging.info("向量库操作系统关闭中...")

def run_app():
    """运行应用"""
    uvicorn.run(
        "vector_system.api.app:app",
        host=WEB_CONFIG["host"],
        port=WEB_CONFIG["port"],
        reload=WEB_CONFIG["reload"],
        workers=WEB_CONFIG["workers"]
    )

if __name__ == "__main__":
    run_app()
